package com.lds.management.center.common.annotation;

import com.lds.management.center.common.util.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Aspect
public class LogAspect {

    @Pointcut("@annotation(Log)")
    public void logPointcut() {
    }

    @Around("logPointcut() && @annotation(logAnnotation)")
    public Object execute(ProceedingJoinPoint joinPoint, Log logAnnotation) throws Throwable {
        String name = logAnnotation.value();
        if (StringUtils.isEmpty(name)) name = joinPoint.getSignature().getName();

        String traceId = UUIDUtils.simpleUuid();

        Map<Integer, Object> request = argsMap(joinPoint.getArgs());
        log.info("[{}]【{}】 start. 请求:{}", traceId, name, request);
        long startTime = System.currentTimeMillis();

        Object result = joinPoint.proceed();

        long endTime = System.currentTimeMillis();
        log.info("[{}]【{}】 end. 耗时{}ms 请求:{} 响应:{}", traceId, name, endTime - startTime, request, result);
        return result;
    }

    private Map<Integer, Object> argsMap(Object[] args) {
        if (args == null || args.length == 0) return null;
        Map<Integer, Object> map = new HashMap<>();

        for (int i = 0; i < args.length; i++) {
            Object arg = args[i];
            map.put(i, arg);
        }
        return map;
    }

}
